/**
 * @author benny.zheng
 * @data 2016-06-06
 * @description 本文件用于方便复制粘贴UI模块之用，请更新这里的说明
 *              另外，考虑到一般是放在js/src/pages/page-name/main.js，因此使用../../
 *              如果不是这个目录，请更改成正确的相对路径
 */
//----------------require--------------

var viewport = require("mlib/dom/viewport"); // viewport
var base = require("mlib/comp/base"); // 基础对象
var parseModule = require("mlib/dom/parseModule"); // 页面模块自动解析

var calendar = require("../plugin/util/calendar");
var ajax = require("mlib/io/ajax");
var animationEnd = require("../plugin/animation/animationEnd");
var swiper = require("mlib/util/swiper");
var touch = require("mlib/evt/touch");
var daterender = require("./calendar.ejs"); 
var Alert = require("../layer/alert"); 

module.exports = function(node, opts) {
    //-----------声明模块全局变量-------------
    var nodeList = null; // 存储所有关键节点
    var that = base();
    var data = null;
    var navIndex=0; 
    var oIndex=0;
    var slider_swiper = null;
    var nav_swiper = null;
    var goods_swiper = null;
    var oldItem = null;
	var m_status =null;
	var m_msg =null;
    //-------------事件响应声明---------------
    var evtFuncs = {
        submitCalendar:function(){
               var timeStr = nodeList.selectday.value,timeArr;
               timeArr = timeStr.split("-");
                custFuncs.sendData({
                    "scheduled_time":timeArr.slice(0,3).join("-"),
                    "price":timeArr[3],
					"goods_id":data.pageid,
					"ocid":data.ocid,
					"status":m_status,
					"msg":m_msg
                });
        },
        switchMoth:function(evt){
            var target = evt.target.closest(".switchMoth"), timeStr = target.getAttribute("data-time"),timeArr;
                timeArr = timeStr.split("-");
                custFuncs.getCalendar(parseInt(timeArr[0]),parseInt(timeArr[1]));
        },
        allowedTap:function(evt){
              var target = evt.target.closest(".day"),timeStr;                   
                    oldItem && oldItem.classList.remove("active");
                    target.classList.add("active");
                    timeStr = target.getAttribute("data-time");
                    nodeList.selectday && (nodeList.selectday.value=timeStr);
                    localStorage.removeItem("dateTime")
                    localStorage.setItem("dateTime",timeStr);
                    oldItem = target;
           },
		   show:function(){
				custFuncs.getCalendar(data.year, data.month,function(){
					nodeList.datepicker.style.display = "block";
					nodeList.mask.style.opacity ="1";
					nodeList.datebox.classList.add("slidein")
					animationEnd(nodeList.datebox, "AnimationEnd", function () {
						nodeList.datebox.classList.remove("slidein");
					}, false);	
				});
		   },
           hide:function(){
                    nodeList.mask.style.opacity ="0";
                    nodeList.datebox.classList.add("slideout")
					animationEnd(nodeList.datebox, "AnimationEnd", function () {
						nodeList.datebox.classList.remove("slideout")
                        nodeList.datepicker.style.display ="none";
                        nodeList.datebox.innerHTML = "";
					}, false);	
           }
    }

    //-------------子模块实例化---------------
    var initMod = function() {
        nav_swiper = new swiper('#nav-swiper',{
            watchSlidesProgress : true,
            watchSlidesVisibility : true,
            slidesPerView : 2,
            onInit: function(swiper){
				
				var vnum = swiper.params.slidesPerView,sw=(document.documentElement.clientWidth/viewport.rem()/vnum)-1.4,cpos=(sw-2.4)/2;
			   [].slice.call(swiper.slides).forEach(function(item,index){
					var itempos =new Number(index*sw+cpos).toFixed(2);
						item.setAttribute("data-pos",itempos);
				   if(index==0){
					   item.classList.add("active-nav");
					   nodeList.navbar.style.cssText="visibility:visible;-webkit-transform:"+"translate3d("+ itempos + "rem,0,0);";
				   }                           
			   });    
            },
            "onTap": function(swiper,evt){  
                goods_swiper.slideTo(swiper.clickedIndex); 
                 			
                custFuncs.updateNavPosition();
				custFuncs.updateBarPosition();	

            }
         })
         goods_swiper=new swiper('#detail-swiper',{
            autoHeight: true,
            "effect" : 'fade',
            "fade": {
              "crossFade": true,
            },  

            "lazyLoading" : true,
            touchMoveStopPropagation : false,
            onSlideChangeStart: function(){  
                		
                custFuncs.updateNavPosition(); 
                custFuncs.updateBarPosition();					
            },
            onInit:function(swiper){   
                   [].slice.call(swiper.slides).forEach(function(item,index){
                       if(index==0){
                           swiper.slides[index].style.zIndex = "1";
                       }
                   });    
                                                                
            }
        });
        

    }

    //-------------绑定事件------------------
    var bindEvents = function() {
        touch.on(nodeList.button,"tap",evtFuncs.show);
        touch.on(nodeList.datebox,"tap",".switchMoth",evtFuncs.switchMoth); 
        touch.on(nodeList.datebox,"tap",".allowed",evtFuncs.allowedTap); 
        touch.on(nodeList.datebox,"tap",".submit",evtFuncs.submitCalendar); 
        touch.on(nodeList.datebox,"tap",".close-wrap",evtFuncs.hide);
        touch.on(nodeList.mask,"tap",evtFuncs.hide);
               
    }

    //-------------自定义函数----------------
    var custFuncs = {
			updateBarPosition:function(){
					var left = parseFloat(nav_swiper.slides[navIndex].getAttribute("data-pos"));
						nodeList.navbar.style['-webkit-transform'] = "translate3d("+ left + "rem,0,0)";
			},
			updateNavPosition:function(){
				var activeIndex = goods_swiper.activeIndex,activeNav;
				[].slice.call(nodeList.navitem).forEach(function(item,index){
					if(activeIndex==index){
						 activeNav =item;
						 navIndex = index;
						  item.classList.add("active-nav");
						 goods_swiper.slides[index].style.zIndex = "1";
					}else{
						item.classList.remove("active-nav");
						goods_swiper.slides[index].style.zIndex = "0";
					}
				});
				if (!activeNav.classList.contains('swiper-slide-visible')) {
					if (navIndex>nav_swiper.activeIndex) {
						var thumbsPerNav = Math.floor(nav_swiper.width/activeNav.clientWidth)-1
						nav_swiper.slideTo(navIndex-thumbsPerNav)
					}else {
						nav_swiper.slideTo(navIndex)
					}   
				}
			},
             renderCalendar:function(result){
                var  mothdays = calendar(result.year, result.month).getView();
                var newMothDays = [];
                var priceIndex = 0;
                var prevDays = mothdays.prevDays;
                var lastDaynum = prevDays+mothdays.mDays;

                mothdays.view.forEach(function(item,index){
                    if(index+1<=prevDays){
                        item.prefixM = "old";
                    }else if(index+1>lastDaynum){
                         item.prefixM = "new";
                    }else{
                         result.pricedata[priceIndex] && (item.price = result.pricedata[priceIndex].price,item.isok = result.pricedata[priceIndex].isok,item.prefixM = "day");                   
                          priceIndex++;
                    }
                    newMothDays.push(item); 
                });
                var calendarTemp = daterender({
                    "dateList":newMothDays,
                    "prevM":mothdays.prevM.y+"-"+mothdays.prevM.m,
                    "nexM":mothdays.nextM.y+"-"+mothdays.nextM.m,
                    "curM":result.year+"-"+result.month,
                    "switchMoth":result.year+"年"+result.month+"月",
                    "trarr":newMothDays.length==35 ? [6,13,20,27] : [6,13,20,27,34]
                });
                nodeList.datebox.innerHTML =  calendarTemp;
             },
            sendData:function(result) {

                var name,
                    form = document.createElement("form"),
                    node = document.createElement("input");

                    form.action = "index.php?r=scheduled/scheduled&ocid="+data.ocid;
                    form.method = "post";
                    for(name in result) {
                        node.name  = name;
                        node.value = result[name].toString();
                        form.appendChild(node.cloneNode());
                    }
                    // 表单元素需要添加到主文档中.
                    form.style.display = "none";
                    document.body.appendChild(form);
                    form.submit();
            },
            getCalendar:function(year,month,callback){
				if(that.isLock()) {
					return;
				}
				that.lock();
                ajax({
                    url: "/index.php?r=goods/detail&selectYear="+year+"&selectMonth="+month+"&goods_id="+data.pageid+"&ocid="+data.ocid,
                    timeout: 30000, // 缺少值3秒,
                    data: { selectYear: year,selectMonth:month }, // 仅method=post时生效，如果传入json对象会被转换成queryString，如果传入字符串则会原样发送
                    method: "post", // 默认是get
                    onSuccess: function(result) {
						    that.unLock();	
                            switch(result.status){
                                case 0:
                                   Alert(result.msg);
								   
                                    break;
                                case 2 :
								
									m_status = result.status;
	                                m_msg = result.msg;
                                    custFuncs.renderCalendar({
										"year":result.selectmonthe[0],
										"month":result.selectmonthe[1],
										"pricedata":result.pricedata
									});
									callback && callback();
                                    break;
                                case 3 :
                                  // custFuncs.sendData({"scheduled_time":"2016-06-22","goods_id":result.goods_id,"ocid":result.oc_id,"price":"0.01","msg":result.msg});
                                //  break;
                                case 4 :                                
                                   custFuncs.sendData({
                                        "scheduled_time":result.scheduled_time,
                                        "goods_id":result.goods_id,
                                        "ocid":result.oc_id,
                                        "price":result.price,
                                        "status":result.status,
                                        "msg":result.msg
                                   });
                                   
                                    break;
                            }
                    },
					onError: function(xmlHttp) {
						that.unLock();
					}
                });
            }
    }

    //-------------一切从这开始--------------
    var init = function(_data) {

        data = _data;
        // 根据数据初始化模块
        // opts["render"]({ "title": data["title"] });

        // 找到所有带有node-name的节点
        nodeList = parseModule(node);
        // 子模块实例化
        initMod();
        // 绑定事件
        bindEvents();
    }

    //---------------暴露API----------------
    that.init = init;

    return that;
};